package com.dag.eagleshop.core.dict.service.impl;

import com.alibaba.fastjson.JSON;
import com.dag.eagleshop.core.dict.model.dos.Dict;
import com.dag.eagleshop.core.dict.model.vo.DictVO;
import com.dag.eagleshop.core.dict.service.DictService;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.entity.DictDTO;
import com.enation.app.javashop.framework.redis.RedisConfig;
import com.enation.app.javashop.framework.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;
@Slf4j
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    @Qualifier("systemDaoSupport")
    private DaoSupport daoSupport;

    /**
     * 查询列表
     */
    @Override
    public Page<DictVO> queryDictList(DictVO dictVO) {
        List<Object> term = new ArrayList<>();
        StringBuilder sql = new StringBuilder(" select * from es_dict  where is_delete = 0 ");

        //字典类型
        String type = dictVO.getType();
        if(StringUtil.notEmpty(type)){
            sql.append(" and type = ?");
            term.add(type);
        }
        // 字典描述
        String description = dictVO.getDescription();
        if(StringUtil.notEmpty(description)){
            sql.append(" and description like ?");
            term.add("%" + description + "%");
        }
        // 根据
        sql.append(" order by create_time desc,sort ");

        return this.daoSupport.queryForPage(sql.toString() , dictVO.getPageNo(),  dictVO.getPageSize(),term.toArray());
    }

    /**
     * 添加数据字典
     * @param dict
     */
    @Override
    public void addDict(Dict dict) {
        dict.setCreateTime(new Date());
        dict.setUpdateTime(new Date());
        daoSupport.insert(dict);
    }

    /**
     * 修改数据字典
     */
    @Override
    public void updateDict(Dict dict) {
        dict.setUpdateTime(new Date());
        Map<String,Object> where = new HashMap<>();
        where.put("id",dict.getId());
        daoSupport.update("es_dict",dict,where);
    }

    /**
     * 根据id删除(逻辑删除)
     */
    @Override
    public void delDict(Integer id) {
        String sql = "update es_dict set is_delete = 1 where id = ? ";
        daoSupport.execute(sql,id);
    }

    /**
     * 查询所有的字典类型type
     */
    @Override
    public List<String> queryAllType() {
        List<String> list = new ArrayList<>();
        DictVO dictVO1 = new DictVO();
        dictVO1.setPageNo(1);
        dictVO1.setPageSize(1000000);
        List data = queryDictList(dictVO1).getData();
        for (int i = 0; i < data.size(); i++) {
            String type = JSON.parseObject(JSON.toJSON(data.get(i)).toString()).getString("type");
            if(!list.contains(type)){
                list.add(type);
            }
        }
        return list;
    }

    /**
     * 根据id查询数据字典
     */
    @Override
    public DictVO queryDictById(Integer id) {
        String sql = "select * from es_dict where id = ? ";
        return daoSupport.queryForObject(sql,DictVO.class,id);
    }

    /**
     * 放入redis缓存中
     */
    @Override
    public synchronized void initDictRedisCache() {
        // 查询所有的数据字典
        List<Dict> dictList = queryAllDict();

        if(IDataUtils.isEmpty(dictList)){
            log.debug("数据库字典为空，初始化失败！");
            return;
        }

        // 封装数据
        Map<String,List<DictDTO>> dictMap = new HashMap<>();
        for (Dict dict : dictList) {
            String type = dict.getType();
            List<DictDTO> dictDTOList = dictMap.get(type);
            DictDTO dictDTO = new DictDTO();
            dictDTOList = dictDTOList == null ? new ArrayList<>() : dictDTOList;
            // 将dict对象的值 赋给dictDTO
            BeanUtil.copyProperties(dict, dictDTO);
            dictDTOList.add(dictDTO);
            dictMap.put(type, dictDTOList);
        }

        // 将字典存放到redis中
        RedisUtils.set(DictUtils.DICT_MAP, dictMap);

        // 发送消息
        RedisUtils.convertAndSend(RedisConfig.REDIS_TOPIC_DICT, "The dictionary cache has been updated.");

    }

    /**
     * 查询所有数据
     */
    public List<Dict> queryAllDict (){
        String sql =" select * from es_dict  where is_delete = 0 order by sort";
        List<Dict> dictList = daoSupport.queryForList(sql, Dict.class);
        return  dictList;
    }

    /**
     * 根据key查询数据字典
     * @param type
     * @return
     */
    @Override
    public Dict queryByType(String type){
        String sql="select * from es_dict  where is_delete = 0 and type = ? order by sort";
        return daoSupport.queryForObject(sql,Dict.class,type);
    }
}
